/*
 *  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 *  reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in
 *  the documentation and/or other materials provided with the
 *  distribution.
 *
 *  3. The end-user documentation included with the redistribution,
 *  if any, must include the following acknowledgment:
 *  "This product includes software developed by the
 *  Sun Microsystems, Inc. for Project JXTA."
 *  Alternately, this acknowledgment may appear in the software itself,
 *  if and wherever such third-party acknowledgments normally appear.
 *
 *  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *  must not be used to endorse or promote products derived from this
 *  software without prior written permission. For written
 *  permission, please contact Project JXTA at http://www.jxta.org.
 *
 *  5. Products derived from this software may not be called "JXTA",
 *  nor may "JXTA" appear in their name, without prior written
 *  permission of Sun.
 *
 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 *  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 *  SUCH DAMAGE.
 *  ====================================================================
 *
 *  This software consists of voluntary contributions made by many
 *  individuals on behalf of Project JXTA.  For more
 *  information on Project JXTA, please see
 *  <http://www.jxta.org/>.
 *
 *  This license is based on the BSD license adopted by the Apache Foundation.
 *
 *  $Id: StripPanel.java,v 1.2 2006/07/13 05:26:36 nano Exp $
 */

package net.jxta.myjxta.misc.beam;

import net.jxta.ext.http.HttpGet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author david.lin@sun.com
 * @version $Id: StripPanel.java,v 1.2 2006/07/13 05:26:36 nano Exp $
 */

public class StripPanel extends javax.swing.JPanel {
    private File input = null;
    private int INTERVAL = 7 * 1000;
    private boolean jButton1IsSelected = false;
    private Timer timer = null;

    /**
     * Creates new form StripPanel
     */
    public StripPanel(File newInput) {
        this.input = newInput;
        initComponents();
    }

    private void init() {
    }

    ;

    private void destroy() {
        stop();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jLabel3 = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText("Sampling Rate:");
        jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        jPanel1.add(jLabel1);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("7");
        jLabel2.setPreferredSize(new java.awt.Dimension(40, 15));
        jPanel1.add(jLabel2);
        jLabel2.getAccessibleContext().setAccessibleName("7");

        jSlider1.setMaximum(180);
        jSlider1.setMinimum(1);
        jSlider1.setValue(7);
        jSlider1.setPreferredSize(new java.awt.Dimension(100, 16));
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jPanel1.add(jSlider1);

        jButton1.setText("Start Poll");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
            }
        });

        jPanel1.add(jButton1);

        add(jPanel1, java.awt.BorderLayout.NORTH);

        jScrollPane1.setViewportView(jLabel3);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

    }
    // </editor-fold>//GEN-END:initComponents

    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MousePressed
// TODO add your handling code here:
        if (jButton1IsSelected) {
            jButton1IsSelected = false;
            jButton1.setText("Start Poll");
            stop();
        } else {
            jButton1IsSelected = true;
            jButton1.setText("Stop Poll");
            start();
        }
    }//GEN-LAST:event_jButton1MousePressed

    // http://www.computing.net/programming/wwwboard/forum/12276.html
    private static ArrayList loadFile(File f) {
        String line;
        ArrayList file = new ArrayList();
        try {
            BufferedReader in = new BufferedReader(new FileReader(f));

            if (!in.ready())
                throw new IOException();

            while ((line = in.readLine()) != null)
                file.add(line);

            in.close();
        }
        catch (IOException e) {
            System.out.println(e);
            return null;
        }

        return file;
    }

    public URL getBeam() {
        //File tempFile = getBeam();
        ArrayList al = loadFile(input);
        String firstLine = (String) al.get(0);
        URL tempURL = null;
        try {
            tempURL = new URL(firstLine);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("tempURL: " + tempURL.toString());
        return tempURL;
    }

    private void setValue(String v) {
        this.jLabel3.setText(v);
        System.out.println("setValue: " + v);
    }

    private void start() {
        //jLabel3.setText("Poll in start state");
        // http://www.docjar.com/docs/api/java/util/TimerTask.html
        this.timer = new Timer();
        TimerTask task = new TimerTask() {
            private HttpGet fetcher = new HttpGet(getBeam());

            public void run() {
                try {
                    setValue(fetcher.dispatch().getBody());
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
        timer.scheduleAtFixedRate(task, 0, INTERVAL);
    }

    private void stop() {
        //jLabel3.setText("Poll in stop state");
        if (this.timer != null) {
            this.timer.cancel();
            this.timer = null;
        }
    }

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        jLabel2.setText(String.valueOf(jSlider1.getValue())); // TODO add your handling code here:
        INTERVAL = 1000 * jSlider1.getValue();
        stop();
        start();
    }//GEN-LAST:event_jSlider1StateChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSlider jSlider1;
    // End of variables declaration//GEN-END:variables

}
